package cn.edu.tju.elm.controller.wallet;

import cn.edu.tju.elm.model.dto.RewardRuleDTO;
import cn.edu.tju.elm.model.RewardRule;
import cn.edu.tju.elm.service.RewardRuleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

@RestController
@RequestMapping("/api/admin/wallet")
@Tag(name = "admin-wallet-controller", description = "管理员钱包管理接口")
public class AdminWalletController {

    @Autowired
    private RewardRuleService rewardRuleService;

    /**
     * 获取奖励规则
     */
    @GetMapping("/reward-rule")
    @Operation(summary = "获取奖励规则", description = "获取唯一的奖励规则")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "获取失败")
    })
    public ResponseEntity<RewardRuleDTO> getRewardRule() {
        try {
            RewardRule rule = rewardRuleService.getRewardRule();
            return ResponseEntity.ok(convertToRewardRuleDTO(rule));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 获取特定权限的奖励规则
     */
    @GetMapping("/reward-rule/{authorityName}")
    @Operation(summary = "获取特定权限的奖励规则", description = "根据权限名称获取奖励规则")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "获取失败")
    })
    public ResponseEntity<RewardRuleDTO> getRewardRuleByAuthority(
            @Parameter(description = "权限名称", required = true) @PathVariable String authorityName) {
        try {
            RewardRule rule = rewardRuleService.getRewardRuleByAuthority(authorityName);
            return ResponseEntity.ok(convertToRewardRuleDTO(rule));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 更新奖励规则（更新普通用户规则 - 保持向后兼容）
     */
    @PutMapping("/reward-rule")
    @Operation(summary = "更新奖励规则", description = "更新唯一的奖励规则")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "400", description = "更新失败")
    })
    public ResponseEntity<RewardRuleDTO> updateRewardRule(
            @Parameter(description = "规则名称", required = true) @RequestParam String ruleName,
            @Parameter(description = "最小充值金额") @RequestParam(required = false) BigDecimal minRechargeAmount,
            @Parameter(description = "奖励金额") @RequestParam(required = false) BigDecimal rewardAmount,
            @Parameter(description = "奖励比例") @RequestParam(required = false) BigDecimal rewardRate,
            @Parameter(description = "提现手续费率") @RequestParam(required = false) BigDecimal withdrawFeeRate) {
        try {
            // 使用兼容方法，默认更新普通用户规则
            RewardRule rule = rewardRuleService.updateRewardRule(
                    ruleName, minRechargeAmount, rewardAmount, rewardRate, withdrawFeeRate);
            return ResponseEntity.ok(convertToRewardRuleDTO(rule));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 更新特定权限的奖励规则
     */
    @PutMapping("/reward-rule/{authorityName}")
    @Operation(summary = "更新特定权限的奖励规则", description = "根据权限名称更新奖励规则")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "400", description = "更新失败")
    })
    public ResponseEntity<RewardRuleDTO> updateRewardRuleByAuthority(
            @Parameter(description = "权限名称", required = true) @PathVariable String authorityName,
            @Parameter(description = "规则名称", required = true) @RequestParam String ruleName,
            @Parameter(description = "最小充值金额") @RequestParam(required = false) BigDecimal minRechargeAmount,
            @Parameter(description = "奖励金额") @RequestParam(required = false) BigDecimal rewardAmount,
            @Parameter(description = "奖励比例") @RequestParam(required = false) BigDecimal rewardRate,
            @Parameter(description = "提现手续费率") @RequestParam(required = false) BigDecimal withdrawFeeRate) {
        try {
            RewardRule rule = rewardRuleService.updateRewardRule(
                    ruleName, authorityName, minRechargeAmount, rewardAmount, rewardRate, withdrawFeeRate);
            return ResponseEntity.ok(convertToRewardRuleDTO(rule));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }

    // DTO转换方法
    private RewardRuleDTO convertToRewardRuleDTO(RewardRule rule) {
        RewardRuleDTO dto = new RewardRuleDTO();
        dto.setId(rule.getId());
        dto.setRuleName(rule.getRuleName());
        dto.setAuthorityName(rule.getAuthorityName()); // 新增字段
        dto.setMinRechargeAmount(rule.getMinRechargeAmount());
        dto.setRewardAmount(rule.getRewardAmount());
        dto.setRewardRate(rule.getRewardRate());
        dto.setWithdrawFeeRate(rule.getWithdrawFeeRate());
        dto.setIsActive(rule.getIsActive());
        dto.setCreateTime(rule.getCreateTime());
        dto.setUpdateTime(rule.getUpdateTime());
        return dto;
    }
}